package com.zkjl.protect_business.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.zkjl.protect_business.common.BaseException;
import com.zkjl.protect_business.common.Status;
import com.zkjl.protect_business.dto.ArchiveDTO;
import com.zkjl.protect_business.entity.Archive;
import com.zkjl.protect_business.entity.Business;
import com.zkjl.protect_business.repository.ArchiveRepository;
import com.zkjl.protect_business.service.ArchiveService;
import com.zkjl.protect_business.service.BusinessService;
import com.zkjl.protect_business.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.BulkByScrollTask;
import org.elasticsearch.index.reindex.ReindexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

import static com.zkjl.protect_business.common.Consts.*;

@Service
@Slf4j
public class ArchiveServiceImpl implements ArchiveService {

    @Autowired
    ArchiveRepository archiveRepository;

    @Autowired
    BusinessService businessService;

    @Autowired
    RestHighLevelClient client;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    LogService logService;


    @Override
    public Archive create(ArchiveDTO archiveDTO, String businessId) {
        String name = archiveDTO.getName();
        Business business = businessService.get(businessId);

        Long docNum = businessService.getDocNum(businessId);
        if (docNum == null || docNum == 0) {
            throw new BaseException(Status.BAD_REQUEST.getCode(), "没有数据可供存档！");
        }


        Boolean isArchive = business.getIsArchive();
        if (isArchive == null || !isArchive) {
            throw new BaseException(Status.BAD_REQUEST.getCode(), "该业务无法创建存档！");
        }

        IndexCoordinates index = businessService.getIndex(businessId);

        String businessName = business.getName();

        String indexName = index.getIndexName();
        String pinyin = PinyinUtil.getPinyin(name, "");
        //存档的新索引
        String newIndexName = ARCHIVE_INDEX_PREFIX + pinyin + "_" + indexName;

        Archive byName = archiveRepository.findByIndexName(newIndexName);
        if (byName != null) {
            throw new BaseException(Status.DATA_EXIST.getCode(), "该存档名称已存在，请更换后重试！");
        }


        Archive archive = new Archive();
        archive.setId(IdUtil.simpleUUID());
        archive.setBusinessId(businessId);
        archive.setBusinessName(business.getName());
        archive.setName(name);
        archive.setIndexName(newIndexName);
        archive.setBaseInfo();

        //转移索引
        //删除索引的逻辑是直接把原来的索引名字改掉
        ReindexRequest reindexRequest = new ReindexRequest();
        reindexRequest.setSourceIndices(index.getIndexName());
        reindexRequest.setDestIndex(newIndexName);
        reindexRequest.setRefresh(true);
        try {
            long l = System.currentTimeMillis();
            BulkByScrollResponse reindex = client.reindex(reindexRequest, RequestOptions.DEFAULT);
            long total = reindex.getTotal();
            BulkByScrollTask.Status status = reindex.getStatus();
            long l1 = System.currentTimeMillis();
            long millis = reindex.getTook().millis();

            log.info("新建【{}】业务存档，文档总数：{},耗时:{}毫秒",businessName,total,l1 -l);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("删除索引失败");
        }

       /* //删除所有数据
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        elasticsearchRestTemplate.delete(queryBuilder.build(),Object.class,index);*/

        archiveRepository.save(archive);

        logService.save("存档", businessName + "的存档" + name, OPERATION_ADD);

        return archive;
    }

    @Override
    public Archive get(String id) {

        Optional<Archive> repository = archiveRepository.findById(id);
        if (!repository.isPresent()) {
            throw new BaseException(Status.DATA_NOT_EXIST.getCode(), "未找到存档信息");
        }

        Archive archive = repository.get();
        return archive;

    }

    @Override
    public Boolean del(String id) {

        Archive archive = get(id);
        String name = archive.getName();
        String businessName = archive.getBusinessName();
        String indexName = archive.getIndexName();
        logService.save("存档", businessName + "的存档" + name, OPERATION_DEL);

        archiveRepository.deleteById(id);
        elasticsearchRestTemplate.deleteIndex(indexName);

        return true;
    }

    @Override
    public List<Archive> list(String businessId) {


        List<Archive> allByBusinessId = archiveRepository.findAllByBusinessId(businessId);

        return allByBusinessId;
    }
}
